package com.view;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.firewarning.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 选择蓝牙的界面
 * Created by wu24 on 2017/9/26.
 */
public class ChoseActivity extends BaseActivity{
    ListView deviceView;
    private ArrayAdapter<String> adapter;
    private ArrayList<String>devices=new ArrayList<>();
    private Map<String,String>map=new HashMap<>();
    private BluetoothAdapter bluetoothAdapter; //本地蓝牙适配器
    ProgressDialog progressDialog;
    private int mode=0;
    private RelativeLayout btnmode1;
    private RelativeLayout btnmdoe2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chose);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null) {
            actionBar.hide();
        }
        ImageView backImage=(ImageView)findViewById(R.id.chose_imageback);
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChoseActivity.this.finish();
            }
        });
        //提示的dialog
        //progressDialog=new ProgressDialog(this);
       // progressDialog.setIndeterminate(false);//循环滚动
       // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
      //  progressDialog.setMessage("正在搜索蓝牙...");
       // progressDialog.setCancelable(false);//false不能取消显示，true可以取消显示
        //progressDialog.show();
       //所有设备
        deviceView=(ListView)this.findViewById(R.id.chose_paireddevice);
        adapter = new Adapter(ChoseActivity.this, R.layout.device_item,devices);
        TextView phoneName=(TextView)this.findViewById(R.id.chose_phone_name);
        phoneName.setText(android.os.Build.MODEL);
        deviceView.setAdapter(adapter);
        deviceView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(mode==0){
                    Toast.makeText(ChoseActivity.this,"请先选择操作",Toast.LENGTH_LONG).show();
                    return;
                }
                Intent intentTemp = new Intent();
                intentTemp.putExtra("name",devices.get(i-1));
                intentTemp.putExtra("address",map.get(devices.get(i-1)));
                intentTemp.putExtra("mode",mode);
                setResult(1,intentTemp);
                finish();
            }
        });
      deviceView.addFooterView(new ViewStub(this));
        deviceView.addHeaderView(new ViewStub(this));
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);
        IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter2);
        //蓝牙是否开启
        if(!bluetoothAdapter.isEnabled())
        {
            bluetoothAdapter.enable();

        }
        //发现设备
      bluetoothAdapter.startDiscovery();
        Set<BluetoothDevice> devicesSet  =bluetoothAdapter.getBondedDevices();
        Iterator<BluetoothDevice> it = devicesSet.iterator();
        while (it.hasNext()) {

            BluetoothDevice device = it.next();
            devices.add(device.getName());
            map.put(device.getName(),device.getAddress());
            adapter.notifyDataSetChanged();

        }


        //选择模式
        btnmode1=(RelativeLayout) this.findViewById(R.id.mode1);
        btnmode1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mode=1;
                Toast.makeText(ChoseActivity.this,"已选择显示浓度",Toast.LENGTH_SHORT).show();
            }
        });
        btnmdoe2=(RelativeLayout) this.findViewById(R.id.mode2);
        btnmdoe2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mode=2;
                Toast.makeText(ChoseActivity.this,"已选择显示坐标",Toast.LENGTH_SHORT).show();
            }
        });
    }


    public void onDestroy() {
        super.onDestroy();
        //解除注册
        unregisterReceiver(mReceiver);
    }



    //定义广播接收
    private BroadcastReceiver mReceiver=new BroadcastReceiver(){



        @Override
        public void onReceive(Context context, Intent intent) {

            String action=intent.getAction();
            if(action.equals(BluetoothDevice.ACTION_FOUND))
            {

                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
              if(device.getBondState()!=BluetoothDevice.BOND_BONDED)
                {
                    devices.add(device.getName());
                    map.put(device.getName(),device.getAddress());
                    adapter.notifyDataSetChanged();

                }

            }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
               // progressDialog.hide();
            }

        }


    };
     class Adapter extends ArrayAdapter{
        private final int resourceId;

        public Adapter(Context context, int textViewResourceId, List<String> devices) {
            super(context, textViewResourceId, devices);
            resourceId = textViewResourceId;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            String device = (String) getItem(position); // 获取当前项实例
            View view = LayoutInflater.from(getContext()).inflate(resourceId, null);//实例化一个对象
            TextView textview = (TextView) view.findViewById(R.id.item_device);//获取该布局内的文本视图
            textview.setText(device);//为文本视图设置文本内容
            return view;
        }
    }
}
